package com.juzipi.thread.test.demo;

/**
 * @Author juzipi
 * @Date 2021/6/16 8:24
 * @Info
 */
public class UnsafeDemo {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"小明").start();
        new Thread(buyTicket,"小军").start();
        new Thread(buyTicket,"小红").start();
        new Thread(buyTicket,"小洁").start();
    }


}
class BuyTicket implements Runnable {

    public static int num = 10;

    boolean flag = true;

    @Override
    public void run() {

        while (flag){
            try {
                Buy();
                //因为sleep不释放线程锁，不能放在synchronized方法下
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private synchronized void Buy() throws InterruptedException {
        if (num <= 0){
            System.out.println("卖完了");
            flag = false;
            return;
        }
//        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"买到了第"+num--+"张票");
    }

}